class TicketsController < ApplicationController
  before_filter :login_required

  def index
    groups = [];
    current_user.groups.each {|group|
    groups << group.id.to_s} if current_user.groups
    if !params[:group]
      @tickets = Ticket.find(:all, :order => 'deadline', :conditions => [ "group_id IN (?)", groups])
    else 
      if groups.include? params[:group]
        @tickets = Ticket.find(:all, :order => 'deadline', :conditions => [ "group_id = (?)", params[:group]])
      else
        @tickets = []
      end
    end
  end

  def find
    if params[:ticket_number] && (@ticket = Ticket.find(:first, :conditions => ["number = (?)" , params[:ticket_number].to_i]))
      redirect_to ticket_path(@ticket)
    else
      flash[:notice] = "Ticket not found"
      redirect_to tickets_path
    end
  end
  
  def clear_closed
    if params[:ticket_template_id]
      conditions = ["ticket_template_id = (?) AND group_id = 0", params[:ticket_template_id]]
      error = false
      if params[:conditions]
        params[:conditions].each {|cond|
          cond[:date].tr_s!("./","-")
          if (['deadline', 'created_at', 'updated_at'].include? cond[:field]) &&  (cond[:date].to_date rescue false)
            conditions[0] += " AND #{cond[:field]} < ?"
            conditions << cond[:date].to_date
          else
            error = true
          end
        }
      end
      if !error
        t_count = Ticket.count(:conditions => conditions)
        Ticket.destroy_all(conditions)
        flash[:notice] = "#{t_count} ticket(s) cleared"
      else
        flash[:notice] = "Please fill in all dates correctly"
      end
    end
    @ticket_templates = TicketTemplate.find(:all)
  end
  
  def change_group
    @ticket = Ticket.find(params[:id])
    @groups = Group.find(:all)
    @heading = 'Change group/Send email'
    return unless request.post?
    @ticket.updated_by = current_user
    @ticket.update_attributes(params[:ticket])
    if params[:send_email] && @ticket.group.emails != [""]
      TicketMailer.deliver_report(@ticket, params[:message], current_user)
    end
    redirect_to tickets_url
  end

  def show
    @ticket = Ticket.find(params[:id])
    redirect_to "/access_denied" if !@ticket || !((current_user.groups.include? @ticket.group) || current_user.admin? || !@ticket.group)
    @heading = 'Showing ticket'
  end

  def new 
    @ticket_templates = TicketTemplate.find(:all)
    @ticket = Ticket.new
    @heading = "New ticket"
  end
  
  def getform
    @ticket_template = TicketTemplate.find(params[:ticket][:ticket_template_id])
    @ticket = Ticket.new(params[:ticket])
    @groups = Group.find(:all)
    notes = []
    @ticket_template.note_types.each {|nt|
      note = Note.new(:note_type => nt, :ticket_id => @ticket)
      note.value = nt.default_v
      notes += [note]
      }
    @ticket.notes=notes.sort_by {|note| note.note_type.priority}
    
    @heading = "New ticket"
    @ticket.deadline = (Time.now+1.week).to_date
    @ticket.group = current_user.groups[0] if current_user.groups
  end

  def create
    @ticket = Ticket.new(params[:ticket])
    @ticket.created_by = current_user
    @ticket.updated_by = current_user
    if @ticket.save
      flash[:notice] = 'Ticket was successfully created'
      redirect_to tickets_url
    else
      @groups = Group.find(:all)
      @heading = "New ticket"
      @ticket_template = @ticket.ticket_template
      render :action => 'getform' 
    end
  end

  def edit
    @ticket = Ticket.find(params[:id])
    redirect_to "/access_denied" if !@ticket || !(current_user.groups.include? @ticket.group)
    @heading = 'Editing ticket'
  end

  def update
    @ticket = Ticket.find(params[:id])
    @ticket.updated_by = current_user
    if !@ticket || !(current_user.groups.include? @ticket.group) 
      redirect_to "/access_denied"
    else 
      if @ticket.update_attributes(params[:ticket])
        flash[:notice] = 'Ticket was successfully updated'
        redirect_to tickets_url
      else
        @groups = Group.find(:all)
        render :action => 'edit'
    end
  end
    
  end

  def destroy
    Ticket.find(params[:id]).destroy
    redirect_to tickets_url
  end
end
